<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class GCMUsers extends MY_Controller {

	function __construct() {

		parent::__construct();
		$this->load->model('GCMModel');
		$this->load->model('T_chat');
	}

	public function index()
	{	
		$data = array();
		$data['resultUsers'] = $this->GCMModel->getAllUsers();
		$NumOfUsers = sizeof($data['resultUsers']);
		$data['num'] = $NumOfUsers;
		$this->load->view('list_user' , $data);
	}

	/**
	 * Logout : change activate field to 0
	 */
	public function logout(){
		//get data post
		$post = $this->input->post();
		//check value post if !=null continue else return false
		parent::check_post_value($post);
		// get data post
		$post = (array) json_decode($post[DATA]);
		$gcm_array = array();
		
		if(isset($post[GCM_REGID])){
			$gcm_array[GCM_REGID] = $post[GCM_REGID];
		}else{
			parent::print_result( 'token is null' , 0 );
			exit();
		}

		$gcm_array[GCM_ACTIVE] = 0;

		$result = $this->GCMModel->updateInfoUserGCM($gcm_array);

		if($result >0){
			parent::print_result( 'logout success' , 1 );
		}else{
			parent::print_result( 'logout failed , try again late' , 0 );
		}
	}

	/**
	 * Register with gcm server
	 */
	public function register_gcm(){

		//get data post
		$post = $this->input->post();
		//check value post if !=null continue else return false
		parent::check_post_value($post);
		// get data post
		$post = (array) json_decode($post[DATA]);
		$gcm_array = array();
		// message return if success
		$message = 'register success!!!';
		
		if(isset($post[GCM_REGID])){
			$gcm_array[GCM_REGID] = $post[GCM_REGID];
		}else{
			parent::print_result( 'token is null' , 0 );
			exit();
		}

		if(isset($post[USER_ID])){
			$gcm_array[USER_ID] = $post[USER_ID];
			$from = $post[USER_ID];
		}else{
			$from = -1;
		}

		if(isset($post[GCM_TYPE])){
			$gcm_array[GCM_TYPE] = $post[GCM_TYPE];
		}else{
			parent::print_result( 'device type unknown' , 0 );
			exit();
		}
		$gcm_array[GCM_ACTIVE] = 1;
		$result = $this->GCMModel->storeUserGCM($gcm_array);

		if( $result > 0){
			$result = $this->send_notification_android(array($gcm_array[GCM_REGID]) , $this->generate_message_gcm($message , 1 , $from, $from));
			$result = json_decode($result, true);
			parent::print_result($result, SUCCESS_VALUE);
		}else{
			parent::print_result( 'insert sida cmnr' , 0 );	
			exit();
		}

	}

	/**
     * Sending Push Notification
     */
    public function send_notification_android($regArray , $msg) {

		$message = array("price" => $msg);
		// $regArray[]=$registatoin_ids;
        // Set POST variables
        $url = 'https://android.googleapis.com/gcm/send';

        $fields = array(
            'registration_ids' => $regArray,
            'data' => $message,
        );

        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }

        // Close connection
        curl_close($ch);
        // echo $result;
        return $result;
    }

    /**
     * Send notificate to a device android
     */
    public function send_notification_a_devices_android($regId , $msg){
    	$this->send_notification_android(array($regId) , $msg);
    }

    /**
     * submit chat & send chat
     */
    public function submit_chat(){
    	//get data post
		$post = $this->input->post();
		//check value post if !=null continue else return false
		parent::check_post_value($post);
		// get data post
		$post = (array) json_decode($post[DATA]);

		if(isset($post[GCM_REGID])){
			$gcm_array[GCM_REGID] = $post[GCM_REGID];
		}else{
			parent::print_result( 'token is null' , 0 );
			exit();
		}

		if(isset($post[MESSAGE]) && strlen($post[MESSAGE]) > 0 ){
			$gcm_array[MESSAGE] = $post[MESSAGE];
		}else{
			parent::print_result( 'message is null' , 0 );
			exit();
		}

		if(isset($post[CHAT_TO]) && strlen($post[CHAT_TO]) > 0 ){
			$gcm_array[CHAT_TO] = $post[CHAT_TO];
		}else{
			parent::print_result( 'not user address to send' , 0 );
			exit();
		}

		$message = $post[MESSAGE];
		$regId = $post[GCM_REGID];
		$to_user_id = $post[CHAT_TO];
		$arr_gcm = $this->GCMModel->getGCMUsers(array( GCM_REGID => $regId ));
		if(count($arr_gcm) > 0){
			$user_post_id = $arr_gcm[0][USER_ID];
		}else{
			parent::print_result('gcm_regid unregister', 0);
		}
		

		$arrFromRegId = $this->GCMModel->getRegIdListFromUserId($user_post_id , $regId);
		$arrFromChatTo = $this->GCMModel->getRegIdListFromUserId($to_user_id);
		$arrMerge = array_merge($arrFromRegId , $arrFromChatTo);

		$result_send = $this-> send_notification_android ($arrMerge , $this->generate_message_gcm( $message , 3 , $user_post_id , $to_user_id) );
		$result_send = json_decode($result_send, true);
		if(isset($result_send[SUCCESS]) && $result_send[SUCCESS] >= 1){

			$data = array();
			$data[CHAT_FROM] = $user_post_id;
			$data[CHAT_TO] = $to_user_id;
			$data[CHAT_CONTENT] = $message;
			$data[CHAT_TYPE] = 3;
		}

		parent::print_result($result_send, SUCCESS_VALUE);
    }

    /**
     * Generate json result of push notification
     */
    public function generate_message_gcm($message , $type , $from = -1 , $to = -1){
    	$mess_array = array( 'type' => $type, 'data' => $message , 'from' => $from , 'to' => $to );

    	return json_encode($mess_array)	;
    }

    /**
     * disconnect all user
     */
    public function disconnect_when_have_change(){
    	//get data post
		$post = $this->input->post();
		//check value post if !=null continue else return false
		parent::check_post_value($post);
		// get data post
		$post = (array) json_decode($post[DATA]);

		if(isset($post[GCM_REGID])){
			$gcm_array[GCM_REGID] = $post[GCM_REGID];
		}else{
			parent::print_result( 'token is null' , 0 );
			exit();
		}

		$regId = $post[GCM_REGID];

		$arr_gcm = $this->GCMModel->getGCMUsers(array( GCM_REGID => $regId ));
		if(count($arr_gcm) > 0){
			$user_post_id = $arr_gcm[0][USER_ID];
		}

		$arrFromRegId = $this->GCMModel->getRegIdListFromUserId($user_post_id , $regId);

		$result_send = $this-> send_notification_android ($arrMerge , $this->generate_message_gcm( 'disconnectted by user' , 0 ) );

    }

}